import os
from datetime import datetime

from aioredis import Redis
from typing_extensions import Annotated

import django


from django.utils.timezone import now
from fastapi import APIRouter, Header, Body, Depends, HTTPException
from pydantic import BaseModel
from starlette.responses import JSONResponse, RedirectResponse

from fastapi_seckill.app_config import app
from fastapi_seckill.tasks import createOrder
from fastapi_seckill.redis_fast import RedisHelper

seckill_api = APIRouter()

class SeckillRequest(BaseModel):
    goodsId: int

# 定义依赖项
async def get_redis_client():
    if not hasattr(app.state, 'redis') or app.state.redis is None:
        raise HTTPException(status_code=500, detail="Redis不可用")
    return app.state.redis  # 返回实际的Redis连接对象

@seckill_api.get('/redis')
async def getRedis(redis: Annotated[RedisHelper, Depends(get_redis_client)] = None):
    redisvalue =await redis.get_cache("goods_detail:2")
    redisvalue=redisvalue["name"]
    return redisvalue
@seckill_api.post("/doSeckill")
async def Seckill(request: SeckillRequest, authorization: str = Header(...),
                  redis: Annotated[RedisHelper, Depends(get_redis_client)] = None):
    goods_id = request.goodsId
    # from fastapi_seckill.main import app
    # redis = app.state.redis  # 使用全局 Redis 客户端


    # 验证用户登录状态
    user_info = await redis.get_cache(authorization.split(' ')[1])
    if not user_info or 'id' not in user_info:
        return JSONResponse({'code': 401, 'message': '登录过期请重新登录'})
    user_id = user_info['id']

    # 获取商品缓存
    goods_key = f'goods_detail:{goods_id}'
    stock_key = f'seckill_stock:{goods_id}'
    goods = await redis.get_cache(goods_key)
    stock = await redis.get_cache(stock_key)

    if not goods or not goods.get('is_seckill'):
        return JSONResponse({'code': 400, 'message': '该商品不是活动商品'})

    now_time = datetime.now()
    start_date = datetime.fromisoformat(goods['start_date'])
    end_date = datetime.fromisoformat(goods['end_date'])
    if not (start_date <= now_time <= end_date):
        return JSONResponse({'code': 400, 'message': '秒杀活动无效或已结束'})

    # 使用 Lua 脚本扣减库存
    remaining_stock = await redis.decrement_stock(stock_key)
    if remaining_stock == -1:
        return JSONResponse({'code': 400, 'message': '库存不足'})

    # 更新商品缓存
    goods['seckill_stock'] = remaining_stock
    goods['stock_count'] -= 1
    await redis.set_cache(goods_key, goods, timeout=3600)
    await redis.set_cache(stock_key, remaining_stock, timeout=3600)


    # 异步创建订单
    createOrder.delay(goods_id, user_id)
    # # 异步创建订单
    # order = await run_in_threadpool(
    #     DjangoORMHelper.create_order,
    #     goods_id,
    #     user_id
    # )
    # # async_create_order.delay(goods_id, user_id)

    return JSONResponse({'code': 200, "message": "秒杀成功，订单正在处理中"})
